/**
 * 管理机
 */
import "reflect-metadata";
import "./common";

/**
 * 管理机的主要职责是 管理本脚本下的所有任务
 */
import { container as injector } from 'tsyringe'
import { Timer } from "./autox/timer";
import { ScriptManager } from "./autox/scriptManager";
import { Sender } from "./autox/sender";
import { CLOUD_CODE, CLOUD_SCRIPT, getDeviceUuid } from "./tokens";
import { WS } from "./autox/ws";
const timer = injector.resolve(Timer)
const sender = injector.resolve(Sender)
const scriptmanager = injector.resolve(ScriptManager)
/**
 * 程序退出自动清理
 */
events.on('exit', () => {
    engines.stopAll();
});
auto.waitFor();
if (!floaty.checkPermission()) {
    floaty.requestPermission()
}
if (device.height === 0 || device.width === 0) {
    toast(
        'Failed to get the screen size. ' +
        'Please try restarting the service or re-installing Hamibot'
    );
    exit();
}
auto.setMode('normal');

/**
 * 检查是否有ws服务
 */
/**
* 保活
*/
timer.setInterval(() => {
    ws.send('ping', new Date().getTime())
}, 3000);

const ws = injector.resolve(WS)
/**
 * 启动
 */
sender.on(CLOUD_CODE, (payload) => {
    try {
        const { id, code, ...config } = payload;
        scriptmanager.start(payload.id, payload.code, config);
    } catch (e) {
        toastLog(`代码执行错误：${e.message}`)
    }
});

sender.on(CLOUD_SCRIPT, (payload) => {
    try {
        const { path, id, ...config } = payload;
        scriptmanager.main(path, id, config);
    } catch (e) {
        toastLog(`代码执行错误：${e.message}`)
    }
});
/**
 * 发送消息到服务器
 */
sender.on<{ type: string, payload: any }>('WEBSOCKET_EMIT', ({ type, payload }) => {
    try {
        const deviceUuid = getDeviceUuid()
        const timestamp = new Date().getTime()
        payload.deviceUuid = deviceUuid;
        payload.timestamp = timestamp;
        payload.type = type;
        ws.send(type, payload);
    } catch (e) {
        toastLog(`发送消息到服务器失败:${e.message}`)
    }
});
/**
 * 启动websocket
 */
try {
    ws.connect();
} catch (e) {
    toastLog(`Websocket连接失败`)
}